package com.grao.waterschool.human.manager.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.grao.waterschool.human.common.BusinessException;
import com.grao.waterschool.human.entiry.vo.GetVideoRequestBody;
import com.grao.waterschool.human.manager.service.ICCVideoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

import static com.grao.waterschool.human.manager.service.impl.ICCAuthorizeServiceImpl.redisTemplate;
import static com.grao.waterschool.human.manager.service.impl.ICCAuthorizeServiceImpl.refreshToken;

@Slf4j
@Service
public class ICCVideoServiceImpl implements ICCVideoService {

    // String getVideoUrl = "https://10.0.25.224/evo-apigw/admin/API/video/stream/realtime";

    String getVideoUrlByRTSP = "https://10.0.25.224/evo-apigw/admin/API/MTS/Video/StartVideo";

    String getPlayBackUrl = "https://10.0.25.224/evo-apigw/admin/API/video/stream/record";
//    String getPlayBackUrl = "https://10.0.25.224/evo-apigw/admin/API/SS/Playback/StartPlaybackByTime";

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    RestTemplate restTemplate;

    /**
     * 根据教室通道Code获取教室直播流
     */
    @Override
    public List<String> getVideoUrl(GetVideoRequestBody requestBody, Integer userId) throws Exception {
        String newToken = refreshToken(userId);
        log.info("提交数据：{}", requestBody);

        long nowTime = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS).toEpochSecond(ZoneOffset.UTC);

        // 解析上课日期和时间
        String sksj = requestBody.getSksj(); // 获取上课时间
        String hour = sksj.substring(0, 2); // 获取小时
        String minute = sksj.substring(2, 4); // 获取分钟

        // 构建完整的上课时间字符串
        String fullSksj = requestBody.getSkrq() + hour + minute; // 组合成 yyyyMMddHHmm

        // 解析上课时间
        LocalDateTime start = LocalDateTime.parse(fullSksj, DateTimeFormatter.ofPattern("yyyyMMddHHmm"));

        DateTimeFormatter formatterForDateTime = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm");
        LocalDateTime skrqSksjDateTime = LocalDateTime.parse(requestBody.getSkrq() + " " + hour + ":" + minute, formatterForDateTime);

        long requestTime = skrqSksjDateTime.toEpochSecond(ZoneOffset.UTC);

        if (nowTime > requestTime) {
            LocalDateTime classEndTime = start.plusMinutes(45);  // 课程结束时间
            log.info("课程结束时间{}", classEndTime);
            return getPlayback(requestBody, newToken, classEndTime);
        } else {
            return getVideo(requestBody, newToken);
        }
    }

    // 将一个yyyyMMddHHmmss格式的时间转换为yyyy-MM-dd HH:mm:ss格式的字符串
    public static String convertToDateFormatted(String dateString) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        LocalDateTime localDateTime = LocalDateTime.parse(dateString, formatter);
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = localDateTime.format(outputFormatter);

        return format;
    }

    private List<String> getPlayback(GetVideoRequestBody requestBody, String token, LocalDateTime classEndTime) throws JsonProcessingException {
        Map<String, Object> data = new HashMap<>();
        data.put("channelId", requestBody.getChannelcode());
        data.put("recordSource", "2");
        data.put("beginTime", convertToDateFormatted(requestBody.getSkrq() + requestBody.getSksj()));
        data.put("endTime", classEndTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        data.put("recordType", "1");
        data.put("type", "rtmp");
        data.put("streamType", "1");

        log.info("--------结束时间------------{}", data.get("endTime"));
        return fetchVideoUrls(data, token, getPlayBackUrl);
    }

    public List<String> getVideo(GetVideoRequestBody requestBody, String token) throws JsonProcessingException {
        Map<String, Object> data = new HashMap<>();
        data.put("channelId", requestBody.getChannelcode());
        data.put("type", "hls");
        data.put("streamType", "1");
        data.put("dataType", "1");

        return fetchVideoUrls(data, token, getVideoUrlByRTSP);
    }

    private List<String> fetchVideoUrls(Map<String, Object> data, String token, String url) throws JsonProcessingException {
        Map<String, Map<String, Object>> outerData = new HashMap<>();
        outerData.put("data", data);
        log.info("发送数据：{}", outerData);
        String jsonRequestBody = objectMapper.writeValueAsString(outerData);

        HttpEntity<String> requestEntity = new HttpEntity<>(jsonRequestBody, getHeaders(token));

        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        log.info("返回：{}", responseEntity.getBody());

        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            String responseBody = responseEntity.getBody();
            if (responseBody != null) {
                return parseResponse(responseBody, token);
            } else {
                throw new BusinessException("响应体为空");
            }
        } else {
            throw new BusinessException("HTTP请求失败，状态码: " + responseEntity.getStatusCode());
        }
    }

    private List<String> parseResponse(String responseBody, String token) {
        try {
            Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
            Integer code = (Integer) responseMap.get("code");
            String desc = (String) responseMap.get("desc");
            if (code == 1000) { // 成功
                Map<String, Object> dataMap = (Map<String, Object>) responseMap.get("data");
                String url = (String) dataMap.get("url");

                String tokens = (String) dataMap.get("token");
                // 分割字符串获取多个链接


                String[] urls = url.split("\\|");
                List<String> urlList = new ArrayList<>();
                for (String singleUrl : urls) {
                    // 为每个链接添加 token 参数
                    if (tokens == null) {
                        String acctssToken = redisTemplate.opsForValue().get("18012accessToken");
                        urlList.add(singleUrl + "?token=" + acctssToken);
                    } else {
                        String urlWithToken = singleUrl + "?token=" + tokens;
                        urlList.add(urlWithToken);
                    }
                    log.info("视频链接：{}", urlList);
                }

                return urlList;
            } else { // 失败
                throw new RuntimeException("请求失败: " + desc);
            }
        } catch (JsonProcessingException | NumberFormatException e) {
            throw new BusinessException("解析响应失败", e);
        }
    }

    private HttpHeaders getHeaders(String token) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("Accept", "*/*");
        headers.add("Authorization", "bearer " + token);
        log.info("headers:{}", headers);
        return headers;
    }
}
